import Compressor from "compressorjs";

// 设置常量
const MAX_FILE_SIZE = 100 * 1024; // 最大文件大小：100KB
const TARGET_WIDTH = 658; // 目标宽度
const TARGET_HEIGHT = 987; // 目标高度
const ASPECT_RATIO = 0.47; // 目标宽高比

/**
 * 创建压缩选项对象
 * @param {boolean} needsCrop - 是否需要裁剪
 * @param {number} quality - 压缩质量
 */
const createCompressorOptions = (needsCrop, quality) => ({
  quality,
  ...(needsCrop && {
    width: TARGET_WIDTH,
    height: TARGET_HEIGHT,
    resize: "cover",
  }),
});

/**
 * 获取图片尺寸
 * @param {File} file - 图片文件
 */
const getImageDimensions = (file) => {
  return new Promise((resolve) => {
    const img = new Image();
    img.src = URL.createObjectURL(file);
    img.onload = () => {
      URL.revokeObjectURL(img.src); // 释放内存
      resolve({ width: img.width, height: img.height });
    };
  });
};

/**
 * 压缩单个图片
 * @param {File} file - 图片文件
 */
const compressSingleImage = async (file) => {
  const { width, height } = await getImageDimensions(file);
  const aspectRatio = width / height;
  const needsCrop = aspectRatio <= ASPECT_RATIO;

  // 如果文件小于限制大小且不需要裁剪，直接返回原文件
  if (file.size <= MAX_FILE_SIZE && !needsCrop) {
    return file;
  }

  // 设置压缩参数
  const quality = file.size <= MAX_FILE_SIZE ? 1 : 0.6;
  const options = createCompressorOptions(needsCrop, quality);

  return new Promise((resolve, reject) => {
    new Compressor(file, {
      ...options,
      success: resolve,
      error: reject,
    });
  });
};

/**
 * 批量压缩图片并重命名
 * @param {Array} files - 图片文件数组
 */
const compressImage = async (files) => {
  try {
    // 压缩所有图片
    const compressedFiles = await Promise.all(
      files.map((item) => compressSingleImage(item.file))
    );

    // 重命名文件
    return compressedFiles.map((file) => {
      const extension = file.name.split(".").pop();
      const newName = `${Date.now()}-${Math.floor(Math.random() * 10000000)}.${extension}`;
      return new File([file], newName, { type: file.type });
    });
  } catch (error) {
    throw new Error("图片压缩失败：" + error.message);
  }
};

export { compressImage };
